import React, {Component} from 'react';
import {
  View,
  Image,
  Text,
  TextInput,
  TouchableOpacity,
  Alert,
  Platform,
  Keyboard,
  Animated,
} from 'react-native';
import dismissKeyboard from 'dismissKeyboard';

import Config from '../../config';
import CommonStyles from '../../common/CommonStyles';
import ToastUtils from '../../common/ToastUtils';
import Constants from '../../common/Constants';
import SizeUtils from '../../common/SizeUtils';
import CommonListPage from '../common/CommonListPage';
import CommonCommentItemView from '../common/CommonCommentItemView';
import CommonDataListView from '../common/CommonDataListView';
import WH_RequestCommentListAction from '../../actions/workhard/WH_RequestCommentListAction';
import NewsRequestCommonListAction from '../../actions/news/NewsRequestCommonListAction';
import WH_SendCommentAction from '../../actions/workhard/WH_SendCommentAction';
import NewsSendCommentAction from '../../actions/news/NewsSendCommentAction';
import NewsSendCommentFollowAction from '../../actions/news/NewsSendCommentFollowAction';
import RequestQuanziCommentListAction from '../../actions/quanzi/RequestQuanziCommentListAction';
import QuanziSendPostCommentAction from '../../actions/quanzi/QuanziSendPostCommentAction';
import LoginCheckIsUserAction from '../../actions/login/LoginCheckIsUserAction';
import PostRequestNewsFollowCommentsAction from '../../actions/post/PostRequestNewsFollowCommentsAction';
import NewsSendCommentListAction from '../../actions/news/NewsSendCommentListAction';
import QZ_CommentShowAction from '../../actions/quanzi/QZ_CommentShowAction';

const ITEM_HEIGHT = 150;

export default class CommonCommentListPage extends CommonListPage {
  constructor(props) {
    super(props);
    this.state.viewStatus = 0;
    this.state.comment = "";
    this.state.keyboardHeight = 0;
    this.state.keyboardHeightAnimate = new Animated.Value(0);
    this._sendingComment = false;

    this._dataKey = "comment_id";
  }

  componentDidMount() {
    this._keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow.bind(this));
    this._keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));

    if(Platform.OS === "ios") {
      this._keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this._keyboardWillHide.bind(this));
    }
    else{
      this._keyboardWillHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardWillHide.bind(this));
    }
    this._keyboardDidChangeListener = Keyboard.addListener('keyboardDidChangeFrame', this._keyboardDidChange.bind(this));
  }

  componentWillUpdate(nextProps, nextState) {
    super.componentWillUpdate(nextProps, nextState);

    if(nextState.commentSuccess) {
      if(this._listView!= null){
        this._listView.doRefresh();
      }
      if (this._getModuleType() == Constants.MODULE_TYPE.QUAN_ZI) {
        ToastUtils.show("发表成功，等待审核通过后显示");
        this.goBack();
      }else{
        ToastUtils.show("发表成功");
      }
      nextState.commentSuccess = false;
      nextState.comment = "";
      this._sendingComment = false;
    }
  }

  componentWillUnmount() {
    this._keyboardWillShowListener.remove();
    this._keyboardDidShowListener.remove();
    this._keyboardWillHideListener.remove();
    this._keyboardDidChangeListener.remove();
  }


  render() {
    return (
      <View style={this._getViewStyle()}>
        {/* <View style={{height:SizeUtils.getWindowSize().heigth + 100}}> */}
          <CommonDataListView style={this._getListViewStyle()}
            ref={(ref) => {this._listView = ref}}
            onPressItem = {this._onPressItem.bind(this)}
            requestData = {this._requestData.bind(this)}
            onRenderItem = {this._onRenderItem.bind(this)}
            onRenderHeader = {this._onRenderHeader.bind(this)}
            onRenderFooter = {this._onRenderFooter.bind(this)}
            noEmpty = {this._noEmpty}
            dataName = {"commentData"}
            updateKey = {"commentLoadComplete"}
          />
        {/* </View> */}
        {this._renderCommentFooter()}
        {this._renderNavigationBar()}
      </View>
    )
  }

  _onRenderFooter() {
    return (
      <View style={{height:SizeUtils.translateDesignHeightToCode(100),
        width:SizeUtils.getWindowSize().width}}>

      </View>
    )
  }

  _getViewStyle() {
    return {paddingTop:Config.paddingTop + SizeUtils.translateDesignHeightToCode(20),
        height:SizeUtils.getWindowSize().heigth,
        backgroundColor:"#ffffff"}
  }

  _getListViewStyle() {
    return {
        width:(SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80)),
        marginLeft:SizeUtils.translateDesignWidthToCode(40),
        height:(SizeUtils.getWindowSize().height - Config.paddingTop - SizeUtils.translateDesignHeightToCode(20)),
        backgroundColor:"#ffffff"};
  }

  _dealEnterPage() {
    if(this._listView != null){
      this._listView.doRefresh();
    }
  }

  _dealLeavePage() {
    dismissKeyboard();
    this._keyboardWillHide();
    this.state.comment = "";
    this._sendingComment = false;
  }

  _getData() {
    return this.props.pageData.routeData.data;
  }
  _getDataItem() {
    return this.props.pageData.routeData.item;
  }

  _renderCommentFooter() {
    return(
      <Animated.View style={{position:"absolute",
        bottom:this.state.keyboardHeightAnimate,
        flexDirection:"row",
        backgroundColor:"#ffffff",
        height:SizeUtils.translateDesignHeightToCode(global.isIphonex?120:98),
        paddingBottom:SizeUtils.translateDesignHeightToCode(global.isIphonex?20:0),
        width:SizeUtils.getWindowSize().width,
        borderWidth:SizeUtils.translateDesignNumToCode(3),
        borderColor:"#e4e4e4", flexDirection:"row", alignItems: "center"}}>
        <TextInput
          style={{padding:0,flex:1,
            fontSize:SizeUtils.translateFontSizeToCode(30),
            paddingLeft:SizeUtils.translateDesignWidthToCode(40),
            paddingRight:SizeUtils.translateDesignWidthToCode(40),
            marginTop:SizeUtils.translateDesignHeightToCode(10),
            }}
          onChangeText = {(comment) => this.setState({comment})}
          placeholder = "发表你的看法"
          multiline = {false}
          onSubmitEditing = {() => this._sendComment()}
          value = {this.state.comment}
          underlineColorAndroid="transparent"
          returnKeyType = "send"
          blurOnSubmit={true}
          enablesReturnKeyAutomatically={true}
        />
         <TouchableOpacity onPress = {() => this._sendComment()}
          disabled = {this.state.viewStatus == 2}
          style = {{ backgroundColor:"#D93338",
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'center',
          height:SizeUtils.translateDesignHeightToCode(98),
          width: SizeUtils.translateDesignWidthToCode(130),
          }}
          >
          <Text style={[CommonStyles.primaryText, {borderWidth:0,
            color: '#ffffff',
            fontSize:SizeUtils.translateFontSizeToCode(30)}]}>
            发表
          </Text>
        </TouchableOpacity>
      </Animated.View>
    )
  }

  _sendComment() {
    if(this.state.comment == "") {
      Alert.alert('提示','评论内容不能为空',[
          {text:'确定',onPress:()=>{}}
        ])
      return;
    }
    if(this._sendingComment === true) {
      return;
    }
    new LoginCheckIsUserAction().call(this, {content:"你是游客身份，不能评论"}, this._onCheckIsUserCallback.bind(this))
  }

  _keyboardWillShow(e){
      this._setKeyboradHeight(e.endCoordinates.height);
  }

  _keyboardDidShow(e) {
      this._setKeyboradHeight(e.endCoordinates.height, 1);
  }

  _keyboardWillHide(e){
      this._setKeyboradHeight(0);
  }

  _keyboardDidChange(e) {
    // ToastUtils.show("键盘高度改变:" + e.endCoordinates.height);
  }

  _setKeyboradHeight(height, duration = 250){
      this.setState({
          keyboardHeight:height
      })
      this._playKeyboardHeightAnimate(height, duration);
      // ToastUtils.show("键盘高度:" + height);
  }

  _playKeyboardHeightAnimate(height, duration) {
    this.state.keyboardHeightAnimate.stopAnimation();
    Animated.timing(          // Uses easing functions
     this.state.keyboardHeightAnimate,    // The value to drive
     {toValue: height, duration:duration},           // Configuration
    ).start();                // Don't forget start!
  }

  _onCheckIsUserCallback(result) {
    if(result) {
      if(this._getModuleType() == Constants.MODULE_TYPE.WORK_HARD) {
        new WH_SendCommentAction().call(this, {post_id:this._getData().post_id, comment:this.state.comment})
      }
      else if(this._getModuleType() == Constants.MODULE_TYPE.NEWS) {
        if (this._getDataItem()) {
          const item = this._getDataItem();
          new NewsSendCommentFollowAction().call(this, {news_id:item.news_id,
              by_user_id:item.by_user_id,
              comment_id:item.comment_id,
              comment:this.state.comment})
        }else{
          new NewsSendCommentAction().call(this, {news_id:this._getData().news_id, comment:this.state.comment})
        }
      }
      else if(this._getModuleType() == Constants.MODULE_TYPE.QUAN_ZI) {
        const item = this._getDataItem();
        let data ={}
        new QuanziSendPostCommentAction().call(this, {
          board_id:this._getData().board_id,
          post_id:this._getData().post_id,
          comment:this.state.comment,
          comment_id:item&&item.comment_id||undefined,
          send_ids:item&&[item.by_user_id]||[],
        })
      }
      else if(this._getModuleType() == Constants.MODULE_TYPE.ZAHUOPU) {
        new ZHP_SendCommentAction().call(this, {post_id:this._getData().post_id, comment:this.state.comment})
      }
      this._sendingComment = true;
    }
  }

  _onPressItem(data) {
    dismissKeyboard();
  }

  _onRenderItem(data) {
    return (<CommonCommentItemView tcomments={this.state.tcomments} data={data}/>)
  }

  _requestData(page, listView) {
    if (this._getDataItem()) {
      const item = this._getDataItem();
      if(this._getModuleType() == Constants.MODULE_TYPE.NEWS) {
        new NewsSendCommentListAction().call(listView, {news_id:item.news_id,
          comment_id:item.comment_id})
      }else if(this._getModuleType() == Constants.MODULE_TYPE.QUAN_ZI) {
        new QZ_CommentShowAction().call(listView, {board_id:item.board_id,post_id:item.post_id,
          comment_id:item.comment_id})
      }
    }else{
      var data = {};
      if(this._getModuleType() == Constants.MODULE_TYPE.WORK_HARD) {
        data = {page:page, page_size:10, post_id:this._getData().post_id};
        new WH_RequestCommentListAction().call(listView, data);
      }
      else if(this._getModuleType() == Constants.MODULE_TYPE.NEWS) {
        data = {page:page, page_size:10, news_id:this._getData().news_id};
        new NewsRequestCommonListAction().call(listView, data);
      }
      else if(this._getModuleType() == Constants.MODULE_TYPE.QUAN_ZI) {
        data = {page:page, page_size:10,
          board_id:this._getData().board_id,
          post_id:this._getData().post_id};
        new RequestQuanziCommentListAction().call(listView, data);
      }
      else if(this._getModuleType() == Constants.MODULE_TYPE.ZAHUOPU) {
        data = {page:page, page_size:10, post_id:this._getData().post_id};
        new ZHP_RequestCommentListAction().call(listView, data);
      }
    }
  }

  _getModuleType() {
    return this.props.pageData.routeData.moduleType;
  }
}
